package com.c2c.controller.login;


import com.c2c.po.User;
import com.c2c.po.enums.impl.UsersState;
import com.c2c.service.AccountService;
import com.sun.deploy.net.HttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
@RequestMapping("/Login")
public class LoginController {

    @Resource
    AccountService accountService;

    @RequestMapping("/userLogin")
    public ModelAndView userLogin(User user, ModelAndView modelAndView, String flag, HttpSession httpSession, HttpServletResponse resp) {
        User byUserAccount = accountService.findByUserAccount(user.getUserAccount());
        if (byUserAccount != null && byUserAccount.getUserState() != UsersState.USER_BAN) {
            if (Objects.equals(byUserAccount.getUserPassword(), user.getUserPassword())) {
                httpSession.setAttribute("userAccount", byUserAccount);
                modelAndView.setViewName("redirect:/Index/push");
                if (flag != null) {
                    Cookie cookie = new Cookie("cookie", byUserAccount.getUserAccount() + "-" + byUserAccount.getUserPassword());
                    cookie.setMaxAge(60 * 60 * 24);
                    resp.addCookie(cookie);
                }
                return modelAndView;
            }
        }
        modelAndView.setViewName("login");
        return modelAndView;
    }


    @RequestMapping("/Register")
    public ModelAndView userRegister(User user, ModelAndView modelAndView, String userPassword1, String userPassword2, String flag) {
        User byUserAccount = accountService.findByUserAccount(user.getUserAccount());
        if (flag != null) {
            if (userPassword1.equals(userPassword2)) {
                if (byUserAccount == null) {
                    user.setUserPassword(userPassword1);
                    accountService.insertUser(user);
                    modelAndView.setViewName("login");
                    return modelAndView;
                }
            }
        }
        modelAndView.setViewName("register");
        return modelAndView;
    }
}
